//! 集群功能的Trait接口定义
//! 
//! 本模块定义了集群功能各层的抽象接口，实现面向接口编程：
//! - 第一层（核心层）：配置管理、节点管理、槽位管理、状态管理
//! - 第二层（协调层）：网络通信、节点发现、命令处理
//! - 第三层（业务逻辑层）：集群协调、故障检测、数据迁移、主从复制

use crate::cluster::ClusterResult;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::time::{Duration, Instant, SystemTime};

// =============================================================================
// 第一层（核心层）Trait接口
// =============================================================================

/// 配置管理接口
#[async_trait]
pub trait ConfigManager: Send + Sync {
    /// 获取节点ID
    fn node_id(&self) -> &str;
    
    /// 获取绑定地址
    fn bind_addr(&self) -> &str;
    
    /// 获取Redis端口
    fn redis_port(&self) -> u16;
    
    /// 获取集群端口
    fn cluster_port(&self) -> u16;
    
    /// 获取种子节点列表
    fn seeds(&self) -> &[String];
    
    /// 验证配置有效性
    fn validate(&self) -> Result<(), String>;
    
    /// 获取Redis服务地址
    fn redis_addr(&self) -> String;
    
    /// 获取集群服务地址
    fn cluster_addr(&self) -> String;
    
    /// 从文件加载配置
    async fn load_from_file<P: AsRef<std::path::Path> + Send>(&mut self, path: P) -> ClusterResult<()>;
    
    /// 保存配置到文件
    async fn save_to_file<P: AsRef<std::path::Path> + Send>(&self, path: P) -> ClusterResult<()>;
}

/// 节点管理接口
#[async_trait]
pub trait NodeManager: Send + Sync {
    /// 节点信息类型
    type Node: NodeInfo;
    
    /// 创建新节点
    async fn create_node(&mut self, id: String, addr: SocketAddr, role: NodeRole) -> ClusterResult<Self::Node>;
    
    /// 获取节点信息
    async fn get_node(&self, id: &str) -> Option<&Self::Node>;
    
    /// 获取可变节点信息
    async fn get_node_mut(&mut self, id: &str) -> Option<&mut Self::Node>;
    
    /// 添加节点
    async fn add_node(&mut self, node: Self::Node) -> ClusterResult<()>;
    
    /// 移除节点
    async fn remove_node(&mut self, id: &str) -> ClusterResult<Option<Self::Node>>;
    
    /// 获取所有节点
    async fn get_all_nodes(&self) -> Vec<&Self::Node>;
    
    /// 获取在线节点数量
    async fn online_node_count(&self) -> usize;
    
    /// 检查节点是否存在
    async fn contains_node(&self, id: &str) -> bool;
    
    /// 更新节点状态
    async fn update_node_state(&mut self, id: &str, state: NodeState) -> ClusterResult<()>;
}

/// 节点信息接口
pub trait NodeInfo: Send + Sync + Clone {
    /// 获取节点ID
    fn id(&self) -> &str;
    
    /// 获取节点地址
    fn addr(&self) -> SocketAddr;
    
    /// 获取节点角色
    fn role(&self) -> &NodeRole;
    
    /// 获取节点状态
    fn state(&self) -> &NodeState;
    
    /// 检查是否为主节点
    fn is_master(&self) -> bool;
    
    /// 检查是否为从节点
    fn is_slave(&self) -> bool;
    
    /// 检查是否在线
    fn is_online(&self) -> bool;
    
    /// 检查是否故障
    fn is_failed(&self) -> bool;
    
    /// 设置节点状态
    fn set_state(&mut self, state: NodeState);
    
    /// 获取管理的槽位
    fn get_slots(&self) -> Vec<u16>;
    
    /// 添加槽位
    fn add_slot(&mut self, slot: u16);
    
    /// 移除槽位
    fn remove_slot(&mut self, slot: u16);
    
    /// 检查是否管理指定槽位
    fn has_slot(&self, slot: u16) -> bool;
}

/// 槽位管理接口
#[async_trait]
pub trait SlotManager: Send + Sync {
    /// 分配槽位给节点
    async fn assign_slot(&mut self, slot: u16, node_id: String) -> ClusterResult<()>;
    
    /// 取消分配槽位
    async fn unassign_slot(&mut self, slot: u16) -> ClusterResult<Option<String>>;
    
    /// 获取槽位对应的节点ID
    async fn get_slot_node(&self, slot: u16) -> Option<&String>;
    
    /// 获取节点管理的所有槽位
    async fn get_node_slots(&self, node_id: &str) -> Vec<u16>;
    
    /// 检查所有槽位是否已分配
    async fn is_fully_covered(&self) -> bool;
    
    /// 获取未分配的槽位
    async fn get_unassigned_slots(&self) -> Vec<u16>;
    
    /// 计算键的槽位
    fn calculate_slot(&self, key: &str) -> u16;
    
    /// 获取槽位统计信息
    async fn get_slot_stats(&self) -> SlotStats;
    
    /// 批量分配槽位
    async fn assign_slots_batch(&mut self, slots: Vec<u16>, node_id: String) -> ClusterResult<()>;
    
    /// 重新平衡槽位分配
    async fn rebalance_slots(&mut self, nodes: &[String]) -> ClusterResult<()>;
}

/// 槽位统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SlotStats {
    pub total_slots: u16,
    pub assigned_slots: u16,
    pub unassigned_slots: u16,
    pub nodes_with_slots: usize,
}

/// 状态管理接口
#[async_trait]
pub trait StateManager: Send + Sync {
    /// 状态类型
    type State: ClusterStateInfo;
    
    /// 获取当前集群状态
    async fn get_state(&self) -> &Self::State;
    
    /// 获取可变集群状态
    async fn get_state_mut(&mut self) -> &mut Self::State;
    
    /// 更新集群状态
    async fn update_state<F>(&mut self, updater: F) -> ClusterResult<()>
    where
        F: FnOnce(&mut Self::State) -> ClusterResult<()> + Send;
    
    /// 保存状态到持久化存储
    async fn save_state(&self) -> ClusterResult<()>;
    
    /// 从持久化存储加载状态
    async fn load_state(&mut self) -> ClusterResult<()>;
    
    /// 获取状态版本号
    async fn get_state_version(&self) -> u64;
    
    /// 检查状态是否一致
    async fn is_state_consistent(&self, other_version: u64) -> bool;
}

/// 集群状态信息接口
pub trait ClusterStateInfo: Send + Sync + Clone {
    /// 获取集群ID
    fn cluster_id(&self) -> &str;
    
    /// 获取当前纪元
    fn current_epoch(&self) -> u64;
    
    /// 获取配置纪元
    fn config_epoch(&self) -> u64;
    
    /// 设置当前纪元
    fn set_current_epoch(&mut self, epoch: u64);
    
    /// 递增配置纪元
    fn increment_config_epoch(&mut self) -> u64;
    
    /// 获取集群大小
    fn size(&self) -> usize;
    
    /// 检查集群是否健康
    fn is_healthy(&self) -> bool;
    
    /// 获取状态摘要
    fn get_summary(&self) -> String;
}

// =============================================================================
// 公共类型定义
// =============================================================================

/// 节点角色
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum NodeRole {
    /// 主节点
    Master,
    /// 从节点 (包含主节点ID)
    Slave(String),
    /// 哨兵节点
    Sentinel,
}

/// 节点状态
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum NodeState {
    /// 在线
    Online,
    /// 离线
    Offline,
    /// 可疑 (部分节点认为离线)
    Suspect,
    /// 确认故障
    Fail,
    /// 握手中
    Handshake,
}

// 只导出必要的类型，避免与trait定义冲突

// =============================================================================
// 第二层（协调层）Trait接口
// =============================================================================

/// 网络通信管理接口
#[async_trait]
pub trait NetworkManager: Send + Sync {
    /// 网络事件类型
    type Event: NetworkEvent;
    /// 网络消息类型
    type Message: NetworkMessage;
    
    /// 启动网络服务
    async fn start(&mut self) -> ClusterResult<()>;
    
    /// 停止网络服务
    async fn stop(&mut self) -> ClusterResult<()>;
    
    /// 绑定到指定地址
    async fn bind(&mut self) -> ClusterResult<()>;
    
    /// 发送消息到指定节点
    async fn send_message(&self, target: &str, message: Self::Message) -> ClusterResult<()>;
    
    /// 广播消息到所有节点
    async fn broadcast_message(&self, message: Self::Message) -> ClusterResult<()>;
    
    /// 接收下一个网络事件
    async fn next_event(&mut self) -> Option<Self::Event>;
    
    /// 设置事件处理器
    fn set_event_handler(&mut self, handler: Box<dyn NetworkEventHandler<Event = Self::Event>>);
    
    /// 获取网络统计信息
    async fn get_stats(&self) -> NetworkStats;
    
    /// 检查连接状态
    async fn is_connected(&self, node_id: &str) -> bool;
    
    /// 建立与节点的连接
    async fn connect_to_node(&mut self, node_id: &str, addr: SocketAddr) -> ClusterResult<()>;
    
    /// 断开与节点的连接
    async fn disconnect_from_node(&mut self, node_id: &str) -> ClusterResult<()>;
}

/// 网络事件接口
pub trait NetworkEvent: Send + Sync + Clone {
    /// 获取事件源节点ID
    fn source_node(&self) -> &str;
    
    /// 获取事件类型
    fn event_type(&self) -> &str;
    
    /// 获取事件时间戳
    fn timestamp(&self) -> Instant;
}

/// 网络消息接口
pub trait NetworkMessage: Send + Sync + Clone {
    /// 获取消息ID
    fn message_id(&self) -> &str;
    
    /// 获取消息类型
    fn message_type(&self) -> &str;
    
    /// 获取消息体
    fn payload(&self) -> &[u8];
    
    /// 设置消息体
    fn set_payload(&mut self, payload: Vec<u8>);
    
    /// 序列化消息
    fn serialize(&self) -> ClusterResult<Vec<u8>>;
    
    /// 反序列化消息
    fn deserialize(data: &[u8]) -> ClusterResult<Self> where Self: Sized;
}

/// 网络事件处理器接口
#[async_trait]
pub trait NetworkEventHandler: Send + Sync {
    type Event: NetworkEvent;
    
    /// 处理网络事件
    async fn handle_event(&mut self, event: Self::Event) -> ClusterResult<()>;
}

/// 网络统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkStats {
    pub total_connections: usize,
    pub active_connections: usize,
    pub messages_sent: u64,
    pub messages_received: u64,
    pub bytes_sent: u64,
    pub bytes_received: u64,
    pub connection_errors: u64,
    pub message_errors: u64,
}

/// 集群协议管理接口
#[async_trait]
pub trait ClusterProtocol: Send + Sync {
    /// 协议消息类型
    type ProtocolMessage: ProtocolMessage;
    
    /// 启动协议处理
    async fn start(&mut self) -> ClusterResult<()>;
    
    /// 停止协议处理
    async fn stop(&mut self) -> ClusterResult<()>;
    
    /// 发送协议消息
    async fn send_protocol_message(&self, target: &str, message: Self::ProtocolMessage) -> ClusterResult<()>;
    
    /// 处理接收到的协议消息
    async fn handle_protocol_message(&mut self, message: Self::ProtocolMessage) -> ClusterResult<()>;
    
    /// 广播协议消息
    async fn broadcast_protocol_message(&self, message: Self::ProtocolMessage) -> ClusterResult<()>;
    
    /// 获取协议统计信息
    async fn get_protocol_stats(&self) -> ProtocolStats;
    
    /// 检查协议版本兼容性
    fn is_version_compatible(&self, version: u16) -> bool;
    
    /// 处理协议版本协商
    async fn negotiate_version(&mut self, peer_version: u16) -> ClusterResult<u16>;
}

/// 协议消息接口
pub trait ProtocolMessage: Send + Sync + Clone {
    /// 获取消息类型
    fn message_type(&self) -> &str;
    
    /// 获取协议版本
    fn protocol_version(&self) -> u16;
    
    /// 获取消息发送者
    fn sender_id(&self) -> &str;
    
    /// 获取消息目标
    fn target_id(&self) -> Option<&str>;
    
    /// 获取消息载荷
    fn payload(&self) -> &[u8];
    
    /// 设置消息载荷
    fn set_payload(&mut self, payload: Vec<u8>);
    
    /// 验证消息有效性
    fn validate(&self) -> bool;
    
    /// 序列化消息
    fn serialize(&self) -> ClusterResult<Vec<u8>>;
    
    /// 反序列化消息
    fn deserialize(data: &[u8]) -> ClusterResult<Self> where Self: Sized;
    
    /// 获取消息所需的可靠性级别
    fn reliability_level(&self) -> ReliabilityLevel;
    
    /// 获取消息优先级
    fn priority(&self) -> MessagePriority;
}

/// 消息可靠性级别
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReliabilityLevel {
    /// 尽力而为 (默认)
    BestEffort,
    /// 至少一次交付
    AtLeastOnce,
    /// 恰好一次交付
    ExactlyOnce,
}

/// 消息优先级
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum MessagePriority {
    /// 低优先级
    Low = 0,
    /// 正常优先级
    Normal = 1,
    /// 高优先级
    High = 2,
    /// 紧急优先级
    Critical = 3,
}

/// 协议统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProtocolStats {
    pub messages_sent: u64,
    pub messages_received: u64,
    pub bytes_sent: u64,
    pub bytes_received: u64,
    pub protocol_errors: u64,
    pub version_mismatches: u64,
    pub reliability_retries: u64,
    pub average_latency: Duration,
    pub peak_latency: Duration,
    pub current_protocol_version: u16,
    pub supported_versions: Vec<u16>,
}

/// 节点发现接口
#[async_trait]
pub trait NodeDiscovery: Send + Sync {
    /// Gossip消息类型
    type GossipMessage: GossipMessage;
    
    /// 启动节点发现
    async fn start(&mut self) -> ClusterResult<()>;
    
    /// 停止节点发现
    async fn stop(&mut self) -> ClusterResult<()>;
    
    /// 发送Gossip消息
    async fn send_gossip(&self, target: &str, message: Self::GossipMessage) -> ClusterResult<()>;
    
    /// 处理接收到的Gossip消息
    async fn handle_gossip(&mut self, message: Self::GossipMessage) -> ClusterResult<()>;
    
    /// 添加种子节点
    async fn add_seed_node(&mut self, addr: SocketAddr) -> ClusterResult<()>;
    
    /// 获取已发现的节点列表
    async fn get_discovered_nodes(&self) -> Vec<SocketAddr>;
    
    /// 主动连接到节点
    async fn meet_node(&mut self, addr: SocketAddr) -> ClusterResult<()>;
    
    /// 忘记节点
    async fn forget_node(&mut self, node_id: &str) -> ClusterResult<()>;
    
    /// 获取Gossip统计信息
    async fn get_gossip_stats(&self) -> GossipStats;
}

/// Gossip消息接口
pub trait GossipMessage: Send + Sync + Clone {
    /// 获取消息发送者节点ID
    fn sender_id(&self) -> &str;
    
    /// 获取消息类型
    fn message_type(&self) -> &str;
    
    /// 获取序号
    fn sequence_number(&self) -> u64;
    
    /// 获取时间戳
    fn timestamp(&self) -> Instant;
    
    /// 验证消息有效性
    fn validate(&self) -> bool;
}

/// Gossip统计信息
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GossipStats {
    pub messages_sent: u64,
    pub messages_received: u64,
    pub nodes_discovered: usize,
    pub seeds_configured: usize,
    pub gossip_rounds: u64,
    #[serde(skip)]
    pub last_gossip_time: Option<Instant>,
}

/// 命令处理接口
#[async_trait]
pub trait CommandProcessor: Send + Sync {
    /// 命令类型
    type Command: ClusterCommand;
    /// 命令结果类型
    type CommandResult: CommandResult;
    
    /// 处理集群命令
    async fn process_command(&mut self, command: Self::Command) -> Self::CommandResult;
    
    /// 批量处理命令
    async fn process_commands_batch(&mut self, commands: Vec<Self::Command>) -> Vec<Self::CommandResult>;
    
    /// 验证命令
    async fn validate_command(&self, command: &Self::Command) -> ClusterResult<()>;
    
    /// 获取支持的命令列表
    fn supported_commands(&self) -> Vec<String>;
    
    /// 获取命令处理统计
    async fn get_command_stats(&self) -> CommandStats;
    
    /// 注册命令处理器
    fn register_command_handler<F>(&mut self, command_type: String, handler: F)
    where
        F: Fn(&Self::Command) -> ClusterResult<Self::CommandResult> + Send + Sync + 'static;
}

/// 集群命令接口
pub trait ClusterCommand: Send + Sync + Clone {
    /// 获取命令类型
    fn command_type(&self) -> &str;
    
    /// 获取命令参数
    fn arguments(&self) -> &[String];
    
    /// 验证命令格式
    fn validate(&self) -> ClusterResult<()>;
    
    /// 序列化命令
    fn serialize(&self) -> ClusterResult<String>;
    
    /// 反序列化命令
    fn deserialize(data: &str) -> ClusterResult<Self> where Self: Sized;
}

/// 命令结果接口
pub trait CommandResult: Send + Sync + Clone {
    /// 检查是否成功
    fn is_success(&self) -> bool;
    
    /// 获取结果数据
    fn data(&self) -> Option<&str>;
    
    /// 获取错误信息
    fn error(&self) -> Option<&str>;
    
    /// 序列化结果
    fn serialize(&self) -> ClusterResult<String>;
}

/// 命令处理统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandStats {
    pub total_commands: u64,
    pub successful_commands: u64,
    pub failed_commands: u64,
    pub commands_by_type: HashMap<String, u64>,
    pub average_processing_time: Duration,
}

// =============================================================================
// 第三层（业务逻辑层）Trait接口
// =============================================================================

/// 集群协调器接口
#[async_trait]
pub trait ClusterCoordinator: Send + Sync {
    /// 启动协调器
    async fn start(&mut self) -> ClusterResult<()>;
    
    /// 停止协调器
    async fn stop(&mut self) -> ClusterResult<()>;
    
    /// 加入集群
    async fn join_cluster(&mut self, seeds: Vec<SocketAddr>) -> ClusterResult<()>;
    
    /// 离开集群
    async fn leave_cluster(&mut self) -> ClusterResult<()>;
    
    /// 处理客户端请求路由
    async fn route_request(&self, key: &str) -> ClusterResult<String>;
    
    /// 获取集群信息
    async fn get_cluster_info(&self) -> ClusterInfo;
    
    /// 执行集群命令
    async fn execute_cluster_command(&mut self, command: String) -> ClusterResult<String>;
    
    /// 检查集群健康状态
    async fn health_check(&self) -> ClusterResult<HealthStatus>;
}

/// 故障检测接口
#[async_trait]
pub trait FailureDetector: Send + Sync {
    /// 启动故障检测
    async fn start(&mut self) -> ClusterResult<()>;
    
    /// 停止故障检测
    async fn stop(&mut self) -> ClusterResult<()>;
    
    /// 报告可疑节点
    async fn report_suspected_node(&mut self, node_id: String, reporter: String);
    
    /// 获取可疑节点列表
    async fn get_suspected_nodes(&self) -> Vec<String>;
    
    /// 清除节点的可疑状态
    async fn clear_suspected_node(&mut self, node_id: &str);
    
    /// 检查节点是否被怀疑
    async fn is_node_suspected(&self, node_id: &str) -> bool;
    
    /// 获取故障检测统计
    async fn get_failure_stats(&self) -> FailureStats;
}

/// 故障恢复接口
#[async_trait]
pub trait FailoverManager: Send + Sync {
    /// 启动故障恢复管理
    async fn start(&mut self) -> ClusterResult<()>;
    
    /// 停止故障恢复管理
    async fn stop(&mut self) -> ClusterResult<()>;
    
    /// 开始选举
    async fn start_election(&mut self) -> ClusterResult<()>;
    
    /// 投票给候选人
    async fn vote_for_candidate(&mut self, candidate_id: &str) -> ClusterResult<()>;
    
    /// 成为主节点
    async fn become_master(&mut self) -> ClusterResult<()>;
    
    /// 获取故障恢复状态
    async fn get_failover_status(&self) -> FailoverStatus;
}

/// 数据迁移接口
#[async_trait]
pub trait DataMigrator: Send + Sync {
    /// 迁移任务类型
    type MigrationTask: MigrationTask;
    
    /// 启动迁移管理器
    async fn start(&mut self) -> ClusterResult<()>;
    
    /// 停止迁移管理器
    async fn stop(&mut self) -> ClusterResult<()>;
    
    /// 创建迁移任务
    async fn create_migration_task(
        &mut self,
        source_node: String,
        target_node: String,
        slots: Vec<u16>,
    ) -> ClusterResult<String>;
    
    /// 开始迁移任务
    async fn start_migration_task(&mut self, task_id: &str) -> ClusterResult<()>;
    
    /// 取消迁移任务
    async fn cancel_migration_task(&mut self, task_id: &str) -> ClusterResult<()>;
    
    /// 获取迁移任务状态
    async fn get_migration_status(&self, task_id: &str) -> Option<MigrationStatus>;
    
    /// 获取所有迁移任务
    async fn get_all_migration_tasks(&self) -> Vec<Self::MigrationTask>;
    
    /// 获取迁移统计信息
    async fn get_migration_stats(&self) -> MigrationStats;
}

/// 迁移任务接口
pub trait MigrationTask: Send + Sync + Clone {
    /// 获取任务ID
    fn task_id(&self) -> &str;
    
    /// 获取源节点
    fn source_node(&self) -> &str;
    
    /// 获取目标节点
    fn target_node(&self) -> &str;
    
    /// 获取迁移的槽位
    fn slots(&self) -> &[u16];
    
    /// 获取任务状态
    fn status(&self) -> &MigrationStatus;
    
    /// 获取进度百分比
    fn progress_percent(&self) -> f64;
    
    /// 获取创建时间
    fn created_at(&self) -> Instant;
}

/// 主从复制接口
#[async_trait]
pub trait ReplicationManager: Send + Sync {
    /// 启动复制管理器
    async fn start(&mut self) -> ClusterResult<()>;
    
    /// 停止复制管理器
    async fn stop(&mut self) -> ClusterResult<()>;
    
    /// 建立主从关系
    async fn replicate_from(&mut self, master_id: String) -> ClusterResult<()>;
    
    /// 添加从节点
    async fn add_slave(&mut self, slave_id: String) -> ClusterResult<()>;
    
    /// 移除从节点
    async fn remove_slave(&mut self, slave_id: &str) -> ClusterResult<()>;
    
    /// 获取从节点列表
    async fn get_slave_list(&self) -> Vec<String>;
    
    /// 获取复制状态
    async fn get_replication_status(&self) -> ReplicationStatus;
    
    /// 获取复制统计信息
    async fn get_replication_stats(&self) -> ReplicationStats;
}

// =============================================================================
// 业务逻辑层数据类型
// =============================================================================

/// 集群信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterInfo {
    pub cluster_id: String,
    pub node_count: usize,
    pub master_count: usize,
    pub slave_count: usize,
    pub slots_assigned: u16,
    pub cluster_state: String,
    pub cluster_size: usize,
}

/// 健康状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthStatus {
    pub is_healthy: bool,
    pub issues: Vec<String>,
    pub recommendations: Vec<String>,
}

/// 故障统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailureStats {
    pub suspected_nodes: usize,
    pub failed_nodes: usize,
    pub detection_cycles: u64,
    pub false_positives: u64,
}

/// 故障恢复状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailoverStatus {
    pub is_in_failover: bool,
    pub current_master: Option<String>,
    pub election_in_progress: bool,
    pub votes_received: u32,
    pub votes_needed: u32,
}

/// 迁移状态
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MigrationStatus {
    Pending,
    InProgress,
    Completed,
    Failed,
    Cancelled,
}

/// 迁移统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationStats {
    pub active_migrations: usize,
    pub completed_migrations: u64,
    pub failed_migrations: u64,
    pub total_data_migrated: u64,
    pub average_migration_time: Duration,
}

/// 复制状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplicationStatus {
    pub role: String,
    pub master_id: Option<String>,
    pub slaves: Vec<String>,
    pub replication_lag: Duration,
    #[serde(skip)]
    pub last_sync: Option<Instant>,
}

/// 复制统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplicationStats {
    pub total_replications: u64,
    pub successful_replications: u64,
    pub failed_replications: u64,
    pub average_lag: Duration,
    pub data_replicated: u64,
}

// ============================================================================
// 第五层：集群应用集成层 (Cluster Application Integration Layer)
// ============================================================================

/// 集群服务器接口 - 第五层核心接口
#[async_trait]
pub trait ClusterServer: Send + Sync {
    /// 启动集群服务器
    async fn start(&mut self) -> ClusterResult<()>;
    
    /// 停止集群服务器
    async fn stop(&mut self) -> ClusterResult<()>;
    
    /// 优雅关闭服务器
    async fn graceful_shutdown(&mut self, timeout: Duration) -> ClusterResult<()>;
    
    /// 获取服务器状态
    async fn get_server_status(&self) -> ClusterServerStatus;
    
    /// 重新加载配置
    async fn reload_config(&mut self, config_path: &str) -> ClusterResult<()>;
    
    /// 获取集群健康状态
    async fn get_cluster_health(&self) -> ClusterHealthStatus;
    
    /// 处理信号
    async fn handle_signal(&mut self, signal: ServerSignal) -> ClusterResult<()>;
    
    /// 获取服务器统计信息
    async fn get_server_stats(&self) -> ClusterServerStats;
}

/// 集群监控接口
#[async_trait]
pub trait ClusterMonitor: Send + Sync {
    /// 开始监控
    async fn start_monitoring(&mut self) -> ClusterResult<()>;
    
    /// 停止监控
    async fn stop_monitoring(&mut self) -> ClusterResult<()>;
    
    /// 获取实时指标
    async fn get_real_time_metrics(&self) -> ClusterMetrics;
    
    /// 获取历史指标
    async fn get_historical_metrics(&self, period: Duration) -> ClusterResult<Vec<ClusterMetrics>>;
    
    /// 注册告警规则
    async fn register_alert_rule(&mut self, rule: AlertRule) -> ClusterResult<()>;
    
    /// 获取活跃告警
    async fn get_active_alerts(&self) -> Vec<Alert>;
    
    /// 导出指标数据
    async fn export_metrics(&self, format: MetricsFormat) -> ClusterResult<String>;
    
    /// 设置监控配置
    async fn set_monitoring_config(&mut self, config: MonitoringConfig) -> ClusterResult<()>;
}

/// 集群压力测试接口
#[async_trait]
pub trait ClusterStressTester: Send + Sync {
    /// 启动压力测试
    async fn start_stress_test(&mut self, config: StressTestConfig) -> ClusterResult<()>;
    
    /// 停止压力测试
    async fn stop_stress_test(&mut self) -> ClusterResult<()>;
    
    /// 获取测试状态
    async fn get_test_status(&self) -> StressTestStatus;
    
    /// 获取测试结果
    async fn get_test_results(&self) -> StressTestResults;
    
    /// 暂停测试
    async fn pause_test(&mut self) -> ClusterResult<()>;
    
    /// 恢复测试
    async fn resume_test(&mut self) -> ClusterResult<()>;
    
    /// 调整测试负载
    async fn adjust_load(&mut self, load_factor: f64) -> ClusterResult<()>;
    
    /// 生成测试报告
    async fn generate_report(&self) -> ClusterResult<String>;
}

/// 服务器状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterServerStatus {
    pub is_running: bool,
    pub start_time: Option<SystemTime>,
    pub uptime: Duration,
    pub cluster_enabled: bool,
    pub node_id: String,
    pub redis_port: u16,
    pub cluster_port: u16,
    pub cluster_state: String,
    pub known_nodes: usize,
}

/// 集群健康状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterHealthStatus {
    pub overall_health: HealthLevel,
    pub cluster_state: String,
    pub total_nodes: usize,
    pub healthy_nodes: usize,
    pub failed_nodes: usize,
    pub slots_assigned: usize,
    pub slots_ok: usize,
    pub slots_pfail: usize,
    pub slots_fail: usize,
    pub is_cluster_stable: bool,
}

/// 健康级别
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum HealthLevel {
    Healthy,
    Warning,
    Critical,
    Unknown,
}

/// 服务器信号
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServerSignal {
    Shutdown,
    Reload,
    Restart,
    Pause,
    Resume,
}

/// 服务器统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterServerStats {
    pub total_connections: u64,
    pub active_connections: usize,
    pub commands_processed: u64,
    pub commands_per_second: f64,
    pub network_input_bytes: u64,
    pub network_output_bytes: u64,
    pub memory_usage: u64,
    pub cpu_usage: f64,
    #[serde(skip, default = "default_instant")]
    pub last_updated: Instant,
}

// Helper function for default Instant
fn default_instant() -> Instant {
    Instant::now()
}

/// 集群指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterMetrics {
    pub timestamp: SystemTime,
    pub cluster_size: usize,
    pub total_slots: usize,
    pub assigned_slots: usize,
    pub active_nodes: usize,
    pub failed_nodes: usize,
    pub total_qps: f64,
    pub total_memory_usage: u64,
    pub average_cpu_usage: f64,
    pub network_throughput: NetworkThroughput,
    pub replication_lag: Duration,
}

/// 网络吞吐量
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkThroughput {
    pub input_bytes_per_sec: f64,
    pub output_bytes_per_sec: f64,
    pub packets_per_sec: f64,
}

/// 告警规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertRule {
    pub id: String,
    pub name: String,
    pub metric: String,
    pub condition: AlertCondition,
    pub threshold: f64,
    pub duration: Duration,
    pub severity: AlertSeverity,
    pub enabled: bool,
}

/// 告警条件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AlertCondition {
    GreaterThan,
    LessThan,
    Equals,
    NotEquals,
}

/// 告警严重程度
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum AlertSeverity {
    Info,
    Warning,
    Critical,
    Emergency,
}

/// 告警
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Alert {
    pub id: String,
    pub rule_id: String,
    pub message: String,
    pub severity: AlertSeverity,
    pub timestamp: SystemTime,
    pub resolved: bool,
    pub metadata: HashMap<String, String>,
}

/// 指标导出格式
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MetricsFormat {
    Json,
    Prometheus,
    Csv,
    InfluxDB,
}

/// 监控配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    pub collection_interval: Duration,
    pub retention_period: Duration,
    pub metrics_endpoint: String,
    pub enable_alerts: bool,
    pub export_format: MetricsFormat,
    pub alert_webhook_url: Option<String>,
}

/// 压力测试配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StressTestConfig {
    pub target_qps: u64,
    pub duration: Duration,
    pub concurrent_clients: usize,
    pub command_mix: HashMap<String, f64>,
    pub data_size_range: (usize, usize),
    pub ramp_up_time: Duration,
    pub cool_down_time: Duration,
}

/// 压力测试状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StressTestStatus {
    pub is_running: bool,
    pub phase: TestPhase,
    pub elapsed_time: Duration,
    pub remaining_time: Option<Duration>,
    pub current_qps: f64,
    pub target_qps: u64,
    pub active_clients: usize,
    pub total_requests: u64,
    pub successful_requests: u64,
    pub failed_requests: u64,
}

/// 测试阶段
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TestPhase {
    Initializing,
    RampingUp,
    Running,
    CoolingDown,
    Completed,
    Failed,
}

/// 压力测试结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StressTestResults {
    pub total_duration: Duration,
    pub total_requests: u64,
    pub successful_requests: u64,
    pub failed_requests: u64,
    pub average_qps: f64,
    pub peak_qps: f64,
    pub average_latency: Duration,
    pub percentile_latencies: HashMap<String, Duration>,
    pub error_distribution: HashMap<String, u64>,
    pub throughput_timeline: Vec<ThroughputPoint>,
}

/// 吞吐量时间点
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThroughputPoint {
    pub timestamp: SystemTime,
    pub qps: f64,
    pub latency: Duration,
    pub errors: u64,
}